<template>
  <a-card
    class="plugin-card"
    :hoverable="true"
    :bordered="true"
    @click="viewPluginDetails"
  >
    <div v-if="plugin.enabled" class="installed-badge">已安装</div>
    <template #cover>
      <div class="plugin-logo">
        <img :src="getPluginLogo(plugin)" alt="插件图标">
      </div>
    </template>
    <a-card-meta>
      <template #title>
        <div class="plugin-title">
          <span>{{ plugin.name }}</span>
          <span class="version-text">版本: {{ plugin.info.version || '-' }}</span>
          <div class="tag-container">
            <a-tag v-if="plugin.hasUpdate" color="orange">有更新</a-tag>
            <a-tag v-if="plugin.pinned" color="blue">置顶</a-tag>
            <div v-if="!plugin.hasUpdate && !plugin.pinned" class="tag-placeholder"></div>
          </div>
        </div>
      </template>
      <template #description>
        <div class="plugin-description">
          <p>{{ plugin.info.description }}</p>
          <div class="plugin-meta">
            <div>
              <a-tag v-for="tag in plugin.tags" :key="tag">{{ tag }}</a-tag>
            </div>
          </div>
        </div>
      </template>
    </a-card-meta>
    <div class="plugin-actions">
      <div class="plugin-type">
        <a-tag color="orange"> {{ GettagName(plugin.type) }}</a-tag>
        <a-tag v-if="plugin.core === 'core'" color="arcoblue"> 系统核心</a-tag>
      </div>
      <div class="action-buttons">
        <template v-if="plugin.enabled">
          <IconSettings v-if="plugin.type === 'datasource' || plugin.type === 'app'" class="action-icon icon-settings" @click.stop="openDataSourceModal" />
          <IconDelete v-if="plugin.core !== 'core'" class="action-icon delete-icon" :spin="loading" @click.stop="uninstallPlugin" />
        </template>
        <template v-else>
          <a-tooltip content="安装这个插件">
            <IconPlus class="action-icon icon-settings" :spin="loading" @click.stop="installPlugin" />
          </a-tooltip>
        </template>
      </div>
    </div>
  </a-card>
</template>

<script lang="ts">
import type { PropType } from 'vue'
import { defineComponent, ref } from 'vue'
import { Message, Modal, Notification } from '@arco-design/web-vue'
import {
  IconDelete,
  IconDownload,
  IconPlus,
  IconSettings,
} from '@arco-design/web-vue/es/icon'
import { useRouter } from 'vue-router'
import { TAG_COLORS } from '@arco-design/web-vue/es/tag/interface'
import type { PluginDTO } from '../types/plugin'
import { pluginApi } from '../api/plugin'
import { install, uninstall } from '@/apis/system/plugins'

export default defineComponent({
  name: 'PluginCard',
  components: {
    IconDelete,
    IconSettings,
    IconPlus,
  },
  props: {
    plugin: {
      type: Object as PropType<PluginDTO>,
      required: true,
    },
  },
  emits: ['update', 'install', 'uninstall'],
  setup(props, { emit }) {
    const router = useRouter()
    const loading = ref(false)
    const dataSourceModalVisible = ref(false)
    const dataSourceForm = ref({
      dataSource: '',
    })
    const data = [{
      label: '数据源',
      value: 'datasource',
    }, {
      label: '前端',
      value: 'panel',
    }, {
      label: '应用',
      value: 'app',
    }, {
      label: '系统扩展',
      value: 'ext',
    }]
    // 名称转化
    const GettagName = (tag: string) => {
      return data.find((item) => item.value === tag)?.label
    }
    const installPlugin = async () => {
      try {
        const confirmed = await new Promise((resolve) => {
          Modal.confirm({
            title: '确认安装',
            content: `是否确认安装插件 ${props.plugin.name}?`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => resolve(true),
            onCancel: () => resolve(false),
          })
        })
        if (!confirmed) return

        loading.value = true
        Notification.warning({
          id: 'install_plugin',
          title: '提示',
          content: `正在安装插件[${props.plugin.name}],请等待...`,
          duration: 0,
        })
        await install(props.plugin.id, props.plugin.info.version)
        Message.success(`插件 ${props.plugin.name} 安装成功`)
        setTimeout(() => {
          Notification.success({
            id: 'install_plugin',
            title: '提示',
            content: '插件安装成功!',
            duration: 2000,
          })
        }, 1000)
        emit('install', props.plugin.id)
      } catch (error) {
        Message.error(`安装失败: ${error.message}`)
        setTimeout(() => {
          Notification.error({
            id: 'install_plugin',
            title: '提示',
            content: `插件安装失败：${error.message}`,
            duration: 2000,
          })
        }, 1000)
      } finally {
        loading.value = false
      }
    }

    const uninstallPlugin = async () => {
      try {
        const confirmed = await new Promise((resolve) => {
          Modal.confirm({
            title: '确认删除',
            content: `是否确认删除插件 ${props.plugin.name}?`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => resolve(true),
            onCancel: () => resolve(false),
          })
        })

        if (!confirmed) return

        loading.value = true
        const { success } = await uninstall(props.plugin.id)
        if (success) {
          Message.success(`插件[${props.plugin.name}]删除成功`)
          loading.value = false
          emit('uninstall', props.plugin.id)
        }
      } catch (error) {
        Message.error(`删除失败: ${error.message}`)
      } finally {
        loading.value = false
      }
    }

    // 数据源设置
    const openDataSourceModal = () => {
      const pluginlocalSet = ['wework', 'email', 'caipu-site']
      // 判断是不是本地的，是跳转本地设置
      if (pluginlocalSet.includes(props.plugin.id)) {
      // 将插件名称生成数组
        router.push({ path: `/plugins/set`, query: { tab: props.plugin.id } })
        return
      }
      router.push({ path: `/app/${props.plugin.id}/setting`, query: { } })
    }
    const getPluginLogo = (plugin: PluginDTO) => {
      // 如果插件有自定义logo，优先使用
      if (plugin.info.logos && plugin.info.logos.large) {
        return plugin.info.logos.large
      }

      // 根据插件类型返回默认图标
      const logoMap = {
        datasource: './src/assets/datasource-large.svg',
        panel: './src/assets/panel-large.svg',
        alert: './src/assets/alert-large.svg',
        logs: './src/assets/logs-large.svg',
      }

      return logoMap[plugin.type.toLowerCase() as keyof typeof logoMap] || './src/assets/default-plugin.svg'
    }

    const viewPluginDetails = (event: Event) => {
      // 阻止事件冒泡，避免点击按钮时触发卡片点击事件
      if ((event.target as HTMLElement).closest('.plugin-actions')) {
        return
      }

      // 导航到插件详情页
      router.push(`/plugins/detail/${props.plugin.id}?install=${props.plugin.enabled}`)
    }

    return {
      loading,
      GettagName,
      dataSourceModalVisible,
      dataSourceForm,
      installPlugin,
      uninstallPlugin,
      openDataSourceModal,
      getPluginLogo,
      viewPluginDetails,
    }
  },
})
</script>

<style scoped>
.plugin-card {
  width: 100%;
  height: 100%;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  min-width: 0;
  overflow: hidden;
  margin: 0;
  align-self: stretch;
}

:deep(.arco-card-body) {
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.arco-card-meta) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

:deep(.arco-card-meta-content) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.plugin-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
  border: 2px solid #165DFF;
  cursor: pointer;
}

.installed-badge {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #e8ffea;
  color: #00b42a;
  padding: 4px 8px;
  font-size: 12px;
  border-bottom-left-radius: 4px;
  z-index: 1;
}

.plugin-logo {
  height: 100px; /* 减小高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  overflow: hidden;
  border-radius: 4px 4px 0 0;
}

.plugin-logo img {
  max-width: 80%;
  max-height: 80px;
  object-fit: contain;
}

.plugin-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 4px;
  flex-wrap: wrap;
  margin-bottom: 4px;
  min-height: 24px; /* 固定高度 */
}

.tag-container {
  display: flex;
  align-items: center;
  min-height: 24px; /* 标签的标准高度 */
}

.tag-placeholder {
  min-height: 24px;
  min-width: 10px;
}

.version-text {
  font-size: 14px;
  color: #86909c;
  margin-right: auto;
}

.plugin-description {
  margin-top: 8px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.plugin-description p {
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 20px; /* 减小高度，使卡片更紧凑 */
  line-height: 1.2;
}

.plugin-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px; /* 减小间距 */
  gap: 4px; /* 减小间距 */
  min-height: 24px; /* 减小高度 */
}

.plugin-meta .arco-tag {
  margin-right: 4px;
  background-color: var(--color-fill-2);
  color: var(--color-text-2);
}

.plugin-meta .arco-tag:first-of-type {
  background-color: var(--color-primary-light-1);
  color: var(--color-primary);
}

.plugin-version {
  font-size: 12px;
  color: #86909c;
}

.plugin-actions {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 28px; /* 固定高度 */
}
.plugin-type {
  display: flex;
  align-items: center;
}

.plugin-type .arco-tag {
  margin-right: 4px;
  color: var(--color-primary);
}
.action-buttons {
  display: flex;
  gap: 8px;
}
.action-icon {
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px;
}

.action-icon:hover {
  transform: scale(1.2);
}

.icon-settings {
  color: #165DFF;
}

.icon-settings:hover {
  color: #0e42c2;
}

.icon-download {
  color: #00b42a;
}

.icon-download:hover {
  color: #009a29;
}

.delete-icon {
  color: #f53f3f !important;
}

.delete-icon:hover {
  color: #cb2634;
}
</style>
